﻿using System;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using System.Web;
using System.IO;
using System.Xml;
using System.Xml.Serialization;
using Microsoft.SharePoint.Utilities;
using System.Collections.ObjectModel;
using System.Collections;
using System.Threading;

namespace Sharepoint.PageManifestExtractor
{
    public partial class PageManifest : LayoutsPageBase
    {

        protected override void OnInit(EventArgs e)
        {
            Thread.CurrentThread.CurrentCulture = Common.GetCurrentCulture();
            base.OnInit(e);
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            string pageUrl = string.Empty;
            string pageListId = string.Empty;
            Elements element = null;
            string elementFilePath = string.Empty;
            Collection<SPFile> files = null;
            ArrayList fileElements = new ArrayList();
            //string deserialisedObject = string.Empty;
            ElementsModuleFile moduleFile = null;
            bool fileException = false;
            ArrayList exceptionFiles = new ArrayList();
            bool criticalException = false;
            string erroredFiles = string.Empty;

            //WriteResponse(string.Empty, string.Empty);

            
            try
            {
                if (Request.QueryString[Constants.PageUrlQueryString] != null)
                    pageUrl = Request.QueryString[Constants.PageUrlQueryString].ToString();
                else if (Request.QueryString[Constants.PageListIdQueryString] != null )
                    pageListId = Request.QueryString[Constants.PageListIdQueryString].ToString();

                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    using (SPSite site = new SPSite(SPContext.Current.Web.Url))
                    {
                        using (SPWeb web = site.OpenWeb())
                        {
                            if (!string.IsNullOrEmpty(pageUrl))
                                files = Common.GetFiles(pageUrl);
                            else if (!string.IsNullOrEmpty(pageListId))
                                files = Common.GetAllFiles(pageListId);

                            if (object.Equals(files, null) || files.Count <= 0)
                                throw new Exception(Common.GetLocalizedString("FileNotFoundExceptionMessage"));

                            element = Common.GetElementFromElementsXml();
                            element.Module.Name = Common.GetLocalizedString("YourModuleNameText");
                            element.Module.Url = files[0].InDocumentLibrary ? files[0].DocumentLibrary.Title : string.Empty;

                            foreach (SPFile file in files)
                            {
                                moduleFile = file.GetFileElement();

                                if (!object.Equals(moduleFile, null))
                                    fileElements.Add(moduleFile);
                                else
                                {
                                    fileException = true;
                                    exceptionFiles.Add(file.Name);
                                }
                            }

                            element.Module.Files = (ElementsModuleFile[])fileElements.ToArray(typeof(ElementsModuleFile));

                        }
                    }
                });

                
            }
            catch (Exception ex)
            {
                LoggingService.LogError(Constants.LogCategory, ex.Message);
                criticalException = true;
            }

            //TextBox1.TextMode = System.Web.UI.WebControls.TextBoxMode.MultiLine;


            //TextBox1.Text = Common.UnescapeXML(deserialisedObject);

            
            //Label1.Text = deserialisedObject;

            

            if (fileException)
            {
                foreach (string excpetionsFile in exceptionFiles)
                    erroredFiles += excpetionsFile + " ";
                WriteResponse(element, string.Format(Common.GetLocalizedString("SpecificPageExceptionMessage"),
                    erroredFiles, SPContext.Current.GetToken()));
            }
            else if (criticalException)
            {
                WriteResponse(null, string.Format(Common.GetLocalizedString("CriticalExceptionMessage"),
                    SPContext.Current.GetToken()));
            }
            else
            {
                WriteResponse(element, string.Empty);
            }

        }

        private void WriteResponse(Elements elementsObject, string exceptionMessage)
        {
            
            string deserialisedObject = string.Empty;

            if (!string.IsNullOrEmpty(exceptionMessage))
            {
                txtException.Visible = true;
                txtException.Text = exceptionMessage;
                //return;
            }

            if (!object.Equals(elementsObject,null))
            {
                deserialisedObject = elementsObject.ConvertToString();
                txtPageManifest.Text = Common.UnescapeXML(deserialisedObject);

                foreach (ElementsModuleFile fileElement in elementsObject.Module.Files)
                {
                    txtPageContent.Text += string.Format(Common.GetLocalizedString("LineSeperatorForFileContents"), fileElement.Path);
                    txtPageContent.Text += "\r\n";
                    txtPageContent.Text += fileElement.Contents;
                    txtPageContent.Text += "\r\n\r\n";
                }
            }
        }
    }
}
